package net.crazyadam.audio;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import org.hermit.android.instruments.AudioAnalyser;
import org.hermit.audalyzer.InstrumentPanel;

public class DopplerAnalyser {
    private AudioAnalyser analyser = null;
    private Thread thread;
    /**
     * 声音接收线程继续运行标识位
     */
    private boolean processable = true;
    private InstrumentPanel instrumentPanel;

    public DopplerAnalyser(Activity activity) {
        instrumentPanel = new InstrumentPanel(activity);
        instrumentPanel.setInstruments(InstrumentPanel.Instruments.SPECTRUM);
//        analyser =instrumentPanel.getAudioAnalyser();
        analyser = new AudioAnalyser(instrumentPanel);
        analyser.setSampleRate(Constant.SAMPLE_RATE);
        analyser.setBlockSize(Constant.BLOCK_SIZE);
        analyser.setDecimation(Constant.DECIMATION);
        analyser.setAverageLen(Constant.AVERAGE_LEN);
        analyser.setWindowFunc(Constant.windowFunc);
    }

    /**
     * 声音分析软件开启，一直处于接收状态。
     */
    public void start() {
        analyser.measureStart();
        processable=true;
        thread = new Thread() {
            @Override
            public void run() {
                while (processable) {
                    analyser.doUpdate(System.currentTimeMillis());
                    try {
                        Thread.sleep(Constant.waitingTime());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.start();
    }

    /**
     * 结束声音分析软件
     * @return 频偏大小，单位 Hz
     */
    public float stop() {
        analyser.measureStop();
        processable = false;
        return analyser.getWindow().processData();
    }
}